//
//  KKTopAlertView.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/27.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKTopAlertView.h"

@interface KKTopAlertView()

@property (nonatomic, strong) UILabel *lab_title;

@end

@implementation KKTopAlertView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithHexString: @"FC5858"];
        self.lab_title = [[UILabel alloc] initWithFrame: CGRectMake(15, CGRectGetHeight(frame) - 50, CGRectGetWidth(frame) - 30, 40)];
        self.lab_title.font = [UIFont systemFontOfSize: 15];
        self.lab_title.textColor = [UIColor whiteColor];
        self.lab_title.numberOfLines = 2;
        self.lab_title.textAlignment = NSTextAlignmentCenter;
        [self addSubview: self.lab_title];
    }
    return self;
}
@end


@implementation UIViewController(KKTopAlertView)

- (void)kk_showTopAlertViewWithMessage:(NSString*)message {
    
    CGFloat height = 64.0;
    if (@available(iOS 11.0, *)){
        UIWindow *window = [[UIApplication sharedApplication] delegate].window;
        if (window.safeAreaInsets.bottom > 0.0) {
            height = 88.0;
        }
    }
    
    KKTopAlertView *alertView = [[KKTopAlertView alloc] initWithFrame: CGRectMake(0, -height, SCREEN_WIDTH, height)];
    alertView.lab_title.text = message;
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    [window addSubview: alertView];
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    
    [UIView animateWithDuration: 0.25 animations:^{
        alertView.center = CGPointMake(SCREEN_WIDTH/2.0, height/2.0);
    } completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [UIView animateWithDuration: 0.25 animations:^{
                alertView.center = CGPointMake(SCREEN_WIDTH/2.0, -height/2.0);
            } completion:^(BOOL finished) {
                [alertView removeFromSuperview];
                [[UIApplication sharedApplication] endIgnoringInteractionEvents];
            }];
        });
    }];
}

@end
